package com.ejoysoft.wlanyz.business;

import java.io.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.ejoysoft.common.DbConnect;
import com.ejoysoft.common.Format;
import com.ejoysoft.common.Globa;
import com.ejoysoft.common.UID;

import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
import com.ejoysoft.common.*;
import com.ejoysoft.servlet.LogIn;

public class ResultXML {
	private Globa globa = new Globa();
	private DbConnect dd = new DbConnect();

	public ResultXML() {
	}

	public ResultXML(Globa globa) {
		this.globa = globa;
		dd = globa.db;
	}

	public ResultXML(Globa globa, boolean b) {
		this.globa = globa;
		dd = globa.db;
		
			
	}

	private String strTaskId = "";
	private String strTelephone = "";
	private String strMac = "";
	private String neiFreInterference = "";
	private String sameFreInterference = "";
	private String dtTestTime = "";
	private double relevanceAPSuccessRate = 0;
	private double relevanceAPAvgTime = 0;
	String strTableName = "task_test_result";
	String strTableName1 = "task_info";
	private NodeList nodes = null;
	private int intState = 1;
	
	public int getIntState() {
		return intState;
	}

	public void setIntState(int intState) {
		this.intState = intState;
	}

	public boolean readresult(InputStream is) throws SQLException {// String 
			 
			if(!readerXml(is))
				return false;
			if(!validateTaskId(strTaskId))
				return false;
			//添加数据库信息
			return add();  
		
	}
	
	
	
	public boolean add()throws SQLException{
		String strSql = "";
		boolean result = false;
		try {
			// 把xml写入数据库
			dd.setAutoCommit(false); 
			String deleteSql = "delete from "+strTableName+" where strTaskId='"+strTaskId+"'";
			dd.executeUpdate(deleteSql);//先删除原来的测试结果
			
			String strId = UID.getID();
			strSql = "INSERT INTO "
					+ strTableName
					+ "  (strId, strTaskId, strMac,strPhone, relevanceAPAvgTime , relevanceAPSuccessRate, sameFreInterference, neiFreInterference , dtTestTime,strCreator,dtCreatTime) VALUES (?,?,?,?,?,?,?,?,to_date(?,'yyyy-MM-dd hh24:mi:ss'),?,to_date(?,'yyyy-MM-dd hh24:mi:ss'))";
			dd.prepareStatement(strSql);
			dd.setString(1, strId);
			dd.setString(2, strTaskId);
			dd.setString(3, strMac);
			dd.setString(4, strTelephone);
			dd.setDouble(5, relevanceAPAvgTime);
			dd.setDouble(6, relevanceAPSuccessRate);
			dd.setString(7, sameFreInterference);
			dd.setString(8, neiFreInterference);
			dd.setString(9, dtTestTime);
			dd.setString(10, "system");
			dd.setString(11, Format.getDateTime());
			if (dd.executeUpdate() > 0) {//插入新的测试结果
				if(update()){
					dd.commit();
					dd.setAutoCommit(true);
					result = true;
				Globa.logger0("增加测试信息", "system","", strSql, "测试管理","");
				// System.out.println(globa.userSession.getStrDepart()+globa.loginName+globa.loginIp+floor+CADname+transmitter+num+rsn+xaxes+yaxes+"rrrrrrrrrrrr");
				System.out.println("*************************************************增加测试数据成功");
				}else {
					dd.rollback();
				}
			}else {
				dd.rollback();
			}  
			dd.setAutoCommit(true);
			return result; 
		} catch (Exception e) {
			dd.rollback();
			System.out.println("增加测试信息时出错！！" + e);
			e.printStackTrace();
			return result;
		}
	}
	
	public boolean update() {
		String strSql2 = "";
		try{//修改intState的值为1
		    strSql2 = "update " + strTableName1 + " set intState = ? where strId = ?";
		    dd.prepareStatement(strSql2);
		    dd.setInt(1, intState);
		    dd.setString(2, strTaskId);
		    if (dd.executeUpdate() > 0) {

				Globa.logger0("增加测试信息", "system","", strSql2, "测试管理","");
				// System.out.println(globa.userSession.getStrDepart()+globa.loginName+globa.loginIp+floor+CADname+transmitter+num+rsn+xaxes+yaxes+"rrrrrrrrrrrr");
				System.out
						.println("*************************************************修改intstate字段成功");
				return true;
		    }
		    else {
		    	 System.out.println("修改intstate字段失败");
		    	return false;}
		    
		}catch (Exception e) {
			return false;
		}
	}
	
	
	/**
	 * 
	 * @param InputStream is
	 * @return boolean
	 */
	public boolean readerXml(InputStream is){
		try {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();//解析工厂
		DocumentBuilder db = factory.newDocumentBuilder();
		// f = new File(XML);
		
		Document doc = db.parse(is);// 输入流对象
		Element elmtInfo = doc.getDocumentElement();
		NodeList nodes2 = elmtInfo.getChildNodes();
		if(nodes2==null)
			return false;
		for (int i = 0; i < nodes2.getLength(); i++) {
			Node result = nodes2.item(i); 					
			System.err.println(nodes2.getLength()+":=========================="+ result.getNodeName());
			if(result.getNodeType() == Node.ELEMENT_NODE && result.getNodeName().equals("testResult"))
			nodes = result.getChildNodes();
		}
		if(nodes==null)
			return false;
		for (int i = 0; i < nodes.getLength(); i++) {
			Node result = nodes.item(i); 
			System.err.println(nodes.getLength()+":-------------------------------"+ result.getNodeName());
			if (result.getNodeType() == Node.ELEMENT_NODE && result.getNodeName().equals("strId")) {
				strTaskId = result.getTextContent();
				System.out.println("strTaskId: " + result.getTextContent());
			}
			if (result.getNodeType() == Node.ELEMENT_NODE && result.getNodeName().equals("strTelephone")) {
				strTelephone = result.getTextContent();
				System.out.println("测试号码: " + result.getTextContent());
			}
			if (result.getNodeType() == Node.ELEMENT_NODE && result.getNodeName().equals("strMac")) {
				strMac = result.getTextContent();
				System.out.println("mac地址: " + result.getTextContent());
			}
			if (result.getNodeType() == Node.ELEMENT_NODE && result.getNodeName().equals("relevanceAPAvgTime")) {
				relevanceAPAvgTime = Double.parseDouble(result.getTextContent());
				System.out.println("测试时延: " + result.getTextContent());

			}
			if (result.getNodeType() == Node.ELEMENT_NODE && result.getNodeName().equals("relevanceAPSuccessRate")) {
				relevanceAPSuccessRate = Double.parseDouble(result.getTextContent());
				System.out.println("测试成功率: " + result.getTextContent());

			}
			if (result.getNodeType() == Node.ELEMENT_NODE && result.getNodeName().equals("sameFreInterference")) {
				sameFreInterference = result.getTextContent();
				System.out.println("同频干扰: " + result.getTextContent());

			}
			if (result.getNodeType() == Node.ELEMENT_NODE && result.getNodeName().equals( "neiFreInterference")) {
				neiFreInterference = result.getTextContent();
				System.out.println("临频干扰: " + result.getTextContent());

			}
			if (result.getNodeType() == Node.ELEMENT_NODE && result.getNodeName().equals("dtTestTime")) {
				dtTestTime = result.getTextContent();
				System.out.println("测试时间: " + result.getTextContent());
			}
		}
		return true;
		} catch (ParserConfigurationException e) {
			e.printStackTrace(); 
			return false;
		} catch (SAXException e) {
			e.printStackTrace(); 
			return false;
		} catch (IOException e) {
			e.printStackTrace(); 
			return false;
		} catch (Exception e) {
			e.printStackTrace(); 
			return false;
		}
	}
	
/**
 * 判断taskId的有效性 
 */
	public boolean validateTaskId(String taskId){
		try {
			String where = "where strId = " + taskId;  
            String strSql = "select * from  " + strTableName1 + "  ".concat(where);
            ResultSet rs = dd.executeQuery(strSql);
            if (rs != null && rs.next()){
                if(rs.getString(1).length()>=1)
                return true;//当数据库中有strID=taskId时返回true
                return false;
            }
            	
            else
                return false;
        } catch (Exception e) {
     
		
		return false;
		}
	}
}